<!doctype html>
<html lang="zh_en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>performance check FPS</title>
</head>
<body>
<h1>Performance Testing Game Sprites using HTML5 Canvas</h1>
<p>Testing basic browser performance for <a
        href="http://stackoverflow.com/questions/4842872/web-page-image-move-performance-comparison-style-change-vs-html5-canvas">this
    Stack Overflow question</a>.</p>
<p><label><input type="checkbox" id="full-bg-clear"> Clear Full Background Each Frame?</label></p>
<p id="fps">182.7 fps</p>
<div id="game" style="width: 1024px;">
    <canvas width="1024" height="768"></canvas>
</div>
</body>
<script>



	/*var rendererEvents = window.performance.getEntriesByType("renderer");
	var compositeThreadEvents = window.performance.getEntriesByType("composite");

	var observer = new PerformanceObserver(function(list) {
		console.log('observer', list)
		var perfEntries = list.getEntries();
		for (var i = 0; i < perfEntries.length; i++) {
			console.log(perfEntries[i].initiatorType, perfEntries[i]);
		}
	});
	console.log(observer)
	performance.mark("begin");
	// subscribe to Frame Timing
	observer.observe({entryTypes: ['resource']});*/


	/*window.onload = function () {
		performance.mark("begin");
		var game = document.getElementById('game');
		var fps = document.getElementById('fps');
		var canv = document.getElementsByTagName('canvas')[0];
		var clearAll = document.getElementById('full-bg-clear');
		var ctx = canv.getContext('2d');
		var size = {w: 44, h: 70, frames: 8}
		var bg = new Image;
		bg.onload = function () {
			var sprite = new Image;
			var w = bg.width, h = bg.height;
			canv.width = w;
			canv.height = h;
			game.style.width = w + "px";
			ctx.drawImage(bg, 0, 0);
			sprite.onload = function () {
				var padding = 200;
				var sprites = [];
				for (var i = 0; i < 20; ++i) {
					var s = sprites[i] = {
						x: Math.random() * (w - padding) + padding / 2,
						y: Math.random() * (h - padding) + padding / 2,
						f: Math.round(Math.random() * 3)
					};
				}

				var avgDelay = 0, lastDraw = new Date;
				var drawFrame = function () {
					if (clearAll.checked) {
						ctx.drawImage(bg, 0, 0);
					} else {
						// Clear sprite locations
						for (var i = 0, len = sprites.length; i < len; ++i) {
							var s = sprites[i];
							ctx.drawImage(bg, s.x, s.y, size.w, size.h, s.x, s.y, size.w, size.h);
						}
					}

					// Draw sprites
					for (var i = 0, len = sprites.length; i < len; ++i) {
						var s = sprites[i];
						s.x += Math.random() * 4 - 2;
						s.y += Math.random() * 4 - 2;
						if (s.x + size.w >= w) s.x -= 10;
						if (s.y + size.h >= h) s.y -= 10;
						var offset = (s.f++ % size.frames) * size.w;
						ctx.drawImage(sprite, offset, 0, size.w, size.h, s.x, s.y, size.w, size.h);
					}
					var now = new Date;
					var delay = now - lastDraw;
					avgDelay += (delay - avgDelay) / 10;
					lastDraw = now;
					setTimeout(drawFrame, 0);
				};
				drawFrame();
				setInterval(function () {
					fps.innerHTML = (1000 / avgDelay).toFixed(1) + " fps";
				}, 2000);

			};
			sprite.src = 'http://phrogz.net/tmp/walking-girl2.png';
		};
		bg.src = 'http://phrogz.net/images/other/deskpics/ColdColdVolcano.jpg';
	};*/

	function a() {
		setTimeout(() => {
			var a = performance.mark("begin");
//		debugger
			var textnode=document.createElement("img");
			document.getElementsByTagName('body')[0].appendChild(textnode);
			textnode.setAttribute('src', 'http://phrogz.net/images/other/deskpics/ColdColdVolcano.jpg')

			function print_PerformanceEntries() {
				// Use getEntries() to get a list of all performance entries
				var entriesNamedBegin = performance.getEntriesByName("begin");
				var p = performance.getEntries();
				for (var i=0; i < p.length; i++) {
					console.log("PerformanceEntry[" + i + "]");
					print_PerformanceEntry(p[i]);
				}
			}
			function print_PerformanceEntry(perfEntry) {
				var properties = ["name",
					"entryType",
					"startTime",
					"duration"];

				for (var i=0; i < properties.length; i++) {
					// check each property
					var supported = properties[i] in perfEntry;
					if (supported) {
						var value = perfEntry[properties[i]];
						console.log("... " + properties[i] + " = " + value);
					} else {
						console.log("... " + properties[i] + " = NOT supported");
					}
				}
			}
			print_PerformanceEntries()
		}, 2000);

		setTimeout(() => {
			var rAF = function () {
				return (
					window.requestAnimationFrame ||
					window.webkitRequestAnimationFrame ||
					function (callback) {
						window.setTimeout(callback, 1000 / 60);
					}
				);
			}();

			var frame = 0;
			var allFrameCount = 0;
			var lastTime = Date.now();
			var lastFameTime = Date.now();

			var loop = function () {
				var now = Date.now();
				var fs = (now - lastFameTime);
				var fps = Math.round(1000 / fs);

				lastFameTime = now;
				// 不置 0，在动画的开头及结尾记录此值的差值算出 FPS
				allFrameCount++;
				frame++;

				if (now > 1000 + lastTime) {
					var fps = Math.round((frame * 1000) / (now - lastTime));
					console.log(`${new Date()} 1S内 FPS：`, fps);
					frame = 0;
					lastTime = now;
				};

				rAF(loop);
			}

			loop();
		}, 1000)
    }



	/**
	 ** 得到浏览器每秒帧数fps
	 **
	 ** @Date Mar 13 2013
	 **/
	var showFPS = function(){
		debugger
		var requestAnimationFrame =
			window.requestAnimationFrame || //Chromium
			window.webkitRequestAnimationFrame || //Webkit
			window.mozRequestAnimationFrame || //Mozilla Geko
			window.oRequestAnimationFrame || //Opera Presto
			window.msRequestAnimationFrame || //IE Trident?
			function(callback) { //Fallback function
				window.setTimeout(callback, 1000/60);
			};
		var e,pe,pid,fps,last,offset,step,appendFps;

		fps = 0;
		last = Date.now();
		step = function(){
			offset = Date.now() - last;
			fps += 1;
			if( offset >= 1000 ){
				last += offset;
				appendFps(fps);
				fps = 0;
			}
			requestAnimationFrame( step );
		};
		//显示fps; 如果未指定元素id，默认<body>标签
		appendFps = function(fps){
			if(!e) e=document.createElement('span');
			pe=pid?document.getElementById(pid):document.getElementsByTagName('body')[0];
			e.innerHTML = "fps: " + fps;
			console.log('fps', fps)
			pe.appendChild(e);
		}
		return {
			setParentElementId :  function(id){pid=id;},
			go          :  function(){step();}
		}
	};

//	showFPS().go()


	/*function usePerformanceEntryMethods() {
		console.log("PerformanceEntry tests ...");

		if (performance.mark === undefined) {
			console.log("... performance.mark Not supported");
			return;
		}

		// Create some performance entries via the mark() method
		performance.mark("Begin");
		doWork(50000);
		performance.mark("End");
		performance.mark("Begin");
		doWork(100000);
		performance.mark("End");
		doWork(200000);
		performance.mark("End");

		// Use getEntries() to iterate through the each entry
		var p = performance.getEntries();
		for (var i=0; i < p.length; i++) {
			console.log("Entry[" + i + "]");
			checkPerformanceEntry(p[i]);
		}

		// Use getEntries(name, entryType) to get specific entries
		p = performance.getEntries({name : "Begin", entryType: "mark"});
		for (var i=0; i < p.length; i++) {
			console.log("Begin[" + i + "]");
			checkPerformanceEntry(p[i]);
		}

		// Use getEntriesByType() to get all "mark" entries
		p = performance.getEntriesByType("mark");
		for (var i=0; i < p.length; i++) {
			console.log ("Mark only entry[" + i + "]: name = " + p[i].name +
				"; startTime = " + p[i].startTime +
				"; duration  = " + p[i].duration);
		}

		// Use getEntriesByName() to get all "mark" entries named "Begin"
		p = performance.getEntriesByName("Begin", "mark");
		for (var i=0; i < p.length; i++) {
			console.log ("Mark and Begin entry[" + i + "]: name = " + p[i].name +
				"; startTime = " + p[i].startTime +
				"; duration  = " + p[i].duration);
		}
	}

	usePerformanceEntryMethods()
	function doWork(num) {
		console.log('666666666666666666', num)
    }
	checkPerformanceEntry = item => {
		console.log('666666666666666666', item)
    }*/



/*
var frame = 0;
var lastTime = Date.now();
var lastFameTime = Date.now();
let startTime = window.performance.now(); // 开始时间
var requestAnimationFrame

	function start() {
//		window.requestAnimationFrame(watchFPS)
		setTimeout(function () {
			watchFPS(startTime);
		}, 1000 / 66)
	}

    function watchFPS(startTime) {
        var now = Date.now();
//        var fs = (now - lastFameTime);
//        var fps = (1000 / fs).toFixed(2);
//        lastFameTime = now;
        // 不置 0，在动画的开头及结尾记录此值的差值算出 FPS
        frame++;
        if (frame === 59) {
//        	debugger
        }

        if (now > (lastTime + 1000)) {
            var fps = ((frame * 1000) / (now - lastTime)).toFixed(2);
            console.log(`${new Date()} 1S内 FPS：`, fps);
            frame = 0;
            lastTime = now;
        };

	    requestAnimationFrame(watchFPS)
    }

    const checkObj = {
		start: start
    }

	checkObj.start()
*/

	const checkObj = {
		_fpsCount: 0, // 帧数
		startTime: window.performance.now(), // 运行开始时间
		lastTime: window.performance.now(), // 运行结束时间
		start: start // 开始函数
	}

		checkObj.start()

	function start() {
		watchFPS = () => {
			var now = Date.now();

			// 不置 0，在动画的开头及结尾记录此值的差值算出 FPS
			this._fpsCount++;

			if (now > (this.lastTime + 1000)) {
				console.log(this._fpsCount)
				var fps = ((this._fpsCount * 1000) / (now - this.lastTime)).toFixed(2);
				console.log(`${new Date()} 1S内 FPS：`, fps);
				this._fpsCount = 0;
				this.lastTime = now;
			}

			this.start();
		}


		/*var requestAnimationFrame =
			window.requestAnimationFrame || //Chromium
			window.webkitRequestAnimationFrame || //Webkit
			window.mozRequestAnimationFrame || //Mozilla Geko
			window.oRequestAnimationFrame || //Opera Presto
			window.msRequestAnimationFrame || //IE Trident?
			function (callback) { //Fallback function
				window.setTimeout(callback, 1000 / 60);
			};*/
// console.log(requestAnimationFrame)
//		requestAnimationFrame(watchFPS)

    setTimeout(() => {
			watchFPS();
        /*this.lastTime = window.performance.now(); // 更新结束时间

        // 不置 0，在动画的开头及结尾记录此值的差值算出 FPS
        this._fpsCount++; // 记录帧数

        if (this.lastTime > (this.startTime + 1000)) {
            console.log(this._fpsCount)
            var fps = ((this._fpsCount * 1000) / (this.lastTime - this.startTime)).toFixed(2);
            console.log(`${new Date()} 1S内 FPS：`, fps);
            this._fpsCount = 0;
            this.startTime = this.lastTime;
        }

        this.start(); // 持续监测*/
    }, 1000 / 66)
//	window.requestAnimationFrame(watchFPS)
//		watchFPS();

	}






	let lastTime = performance.now()
	let frame = 0
	let lastFameTime = performance.now()
	const loop = time => {
		let now =  performance.now()
		let fs = (now - lastFameTime)
		lastFameTime = now
		let fps = Math.round(1000 / fs)
		frame++
		if (now > 1000 + lastTime) {
			fps = Math.round(( frame * 1000 ) / ( now - lastTime ))
            console.log(fps)
			frame = 0
			lastTime = now
		}
		window.requestAnimationFrame(loop)
	}
//	window.requestAnimationFrame(loop)


</script>
</html>